import React from 'react'
import { DeviceEventEmitter, Image, ImageBackground } from 'react-native'

import { loading } from '../../util/images.js'
import { ScreenWidth } from '../../util/utils.js'


export default class AutoHeightImage extends React.PureComponent {

    constructor(props) {
        super(props)
        console.log(props)
        this.state = {
            width: props.width || ScreenWidth,
            height: ScreenWidth
        }
    }

    componentDidMount() {
        const { width } = this.state
        console.log(this.props.source.uri)
        Image.getSize(this.props.source.uri, (w, h) => {
            console.log(w, h, 'success')
            this.setState({
                height: width / w * h
            })
        }, (error) => {
            console.log(error, 'error')
        });
    }

    render() {
        const { width, height } = this.state
        if (height && height > 0) {
            return (
                <Image
                    {...this.props}
                    style={{
                        width,
                        height,
                    }}
                    loadingIndicatorSource={loading}
                    resizeMode="stretch"
                />
            )
        }
        return null
    }
}
